package com.yeyks.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yeyks.common.base.Arguments;
import com.yeyks.common.utils.apputil.redis.RedisService;
import com.yeyks.common.utils.apputil.rediskey.BuilderKey;
import com.yeyks.common.utils.apputil.rediskey.RedisKey;
import com.yeyks.search.pojo.model.EsHotelInfo;
import com.yeyks.search.pojo.model.EsRoomCalendarInfo;
import com.yeyks.search.pojo.model.EsRoomInfo;
import com.yeyks.search.pojo.param.EsC2bHotelSearchParam;
import com.yeyks.search.pojo.param.EsHotelSearchParam;
import com.yeyks.search.service.ElasticSearchService;
import com.yeyks.common.ajax.AjaxResponseBody;
import com.yeyks.search.service.MySearchService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.List;
import java.util.Map;

/**
 * es接口
 *
 * @author: shuai
 * @date: 2019/9/27 0023 9:55
 */
@Api(tags = "es接口")
@RestController
@RequestMapping("/es")
@Slf4j
public class EsController {

    @Autowired
    private ElasticSearchService elasticSearchService;
    @Autowired
    private MySearchService mySearchService;
    @Autowired
    private RedisService redisService;

    @ApiOperation("创建索引")
    @GetMapping("/create/index")
    public AjaxResponseBody createIndex(String indexName) {
        IndexResponse index = elasticSearchService.createIndex(indexName);
        return AjaxResponseBody.success(index);
    }

    @ApiOperation("创建文档")
    @GetMapping("/create/document")
    public AjaxResponseBody createDocument(String indexName, String id, String orderNo, String orderName) {
        Map<String, Object> map = Maps.newHashMap();
        map.put("id", id);
        map.put("orderNo", orderNo);
        map.put("orderName", orderName);
        return AjaxResponseBody.success(elasticSearchService.createDocument(map, indexName, "id"));
    }

    @ApiOperation("更新文档")
    @GetMapping("/update/document")
    public AjaxResponseBody updateDocument(String indexName, String id, String orderNo, String orderName) {
        Map<String, Object> map = Maps.newHashMap();
        map.put("id", id);
        map.put("orderNo", orderNo);
        map.put("orderName", orderName);
        return AjaxResponseBody.success(elasticSearchService.updateDocument(map, indexName, "id"));
    }

    @ApiOperation("删除文档")
    @GetMapping("/del/document")
    public AjaxResponseBody delDocument(String indexName, String id) {
        DeleteResponse deleteResponse = elasticSearchService.deleteDocument(indexName, id);
        return AjaxResponseBody.success(deleteResponse);
    }

    @ApiOperation("酒店条件查询")
    @GetMapping("/hotel/search")
    public AjaxResponseBody hotelSearch(String name, String address, Integer starLevel, String hotelId, String sourceId) {
        EsHotelSearchParam param = new EsHotelSearchParam();
        param.setName(name);
        param.setAddress(address);
        param.setStarLevel(starLevel);
        param.setHotelId(hotelId);
        param.setSourceId(sourceId);
        return AjaxResponseBody.success(mySearchService.searchHotel(param));
    }

    @ApiOperation("c2b酒店条件查询")
    @GetMapping("/c2b/hotel/search")
    public AjaxResponseBody c2bHotelSearch(String city,
                                           Integer price,
                                           String startDate,
                                           String endDate,
                                           Integer manualPickOrder, Double x, Double y) throws ParseException {
        EsC2bHotelSearchParam param = new EsC2bHotelSearchParam();
        param.setCity(city);
        if (null == x && null == y) {
            param.setPositionX(120.4342287385);
            param.setPositionY(30.237791384941);
        } else {
            param.setPositionX(x);
            param.setPositionY(y);
        }
        param.setPrice(price);
        param.setManualPickOrder(manualPickOrder);
        param.setStartDate(DatePattern.NORM_DATE_FORMAT.parse(startDate));
        param.setEndDate(DatePattern.NORM_DATE_FORMAT.parse(endDate));
        return AjaxResponseBody.success(mySearchService.c2bSearchStepHotel(param));
    }

    @ApiOperation("房态条件查询")
    @PostMapping("/calendar/search")
    public AjaxResponseBody c2bCalendarSearch(@RequestParam(value = "indexName")String indexName,
                                              @RequestParam(value = "sourceType", defaultValue = "cn") String sourceType,
                                              @RequestParam(value = "calendarId", defaultValue = "", required = false) String calendarId,
                                              @RequestParam(value = "pageSize", defaultValue = "100")Integer pageSize,
                                              @RequestParam(value = "pageNo", defaultValue = "1")Integer pageNo) {


        return AjaxResponseBody.success(elasticSearchService.c2bSearchCalendar(indexName, sourceType, calendarId, pageSize, pageNo));
    }

    @ApiOperation("房间条件查询")
    @PostMapping("/room/search")
    public AjaxResponseBody esRoomSearch(     @RequestParam(value = "indexName")String indexName,
                                              @RequestParam(value = "sourceType", defaultValue = "cn") String sourceType,
                                              @RequestParam(value = "roomId", defaultValue = "", required = false) String roomId,
                                              @RequestParam(value = "pageSize", defaultValue = "100")Integer pageSize,
                                              @RequestParam(value = "pageNo", defaultValue = "1")Integer pageNo) {


        return AjaxResponseBody.success(elasticSearchService.esRoomSearch(indexName, sourceType, roomId, pageSize, pageNo));
    }

    @ApiOperation("给城市添加上浮下浮比例")
    @PostMapping("/city/percent")
    public AjaxResponseBody addCityPercent(@RequestParam(value = "provinceId")String provinceId,
                                           @RequestParam(value = "cityId") String cityId,
                                           @RequestParam(value = "highPercent", defaultValue = "0.95") String highPercent,
                                           @RequestParam(value = "lowPercent", defaultValue = "0.75") String lowPercent){

        AjaxResponseBody body = AjaxResponseBody.failed();

        String redisKey = BuilderKey.build(RedisKey.CITY_PERCENT_PRICE, provinceId+":"+cityId);
        String redisValue = lowPercent + "-" + highPercent;
        if(Arguments.strNotNull(provinceId) && Arguments.strNotNull(cityId)
                && Arguments.strNotNull(highPercent) && Arguments.strNotNull(lowPercent)){
            redisService.set(redisKey, redisValue);
            body = AjaxResponseBody.success();
        }
        return body;

    }

    @ApiOperation("由酒店ID查询房间")
    @PostMapping("/get/hotel/child/sourceId")
    public AjaxResponseBody getHotelChildBySourceId(@RequestParam(value = "hotelSourceId")String hotelSourceId,
                                                    @RequestParam(value = "indexName") String indexName){
        AjaxResponseBody body = AjaxResponseBody.success();
        List<EsRoomInfo> esRoomInfoList = elasticSearchService.queryByParentId(hotelSourceId, indexName);
        body.setBody(esRoomInfoList);

        return body;
    }

    @ApiOperation("由房间ID查询房态")
    @PostMapping("/get/room/child/sourceId")
    public AjaxResponseBody getRoomChildBySourceId(@RequestParam(value = "roomSourceId")String roomSourceId,
                                                    @RequestParam(value = "indexName") String indexName){
        AjaxResponseBody body = AjaxResponseBody.success();
        List<EsRoomCalendarInfo> esRoomCalendarInfoList = elasticSearchService.queryCalendarByParentId(roomSourceId, indexName);
        body.setBody(esRoomCalendarInfoList);

        return body;
    }

    //检验所有房间,如果没有房态，直接删除
    @ApiOperation("由房间ID查询房态")
    @PostMapping("/del/room/calendarIsNull")
    public AjaxResponseBody checkCalendar(@RequestParam(value = "pageNo", defaultValue = "1")Integer pageNo,
                                          @RequestParam(value = "indexName", defaultValue = "index_hotel") String indexName,
                                          @RequestParam(value = "pageSize", defaultValue = "2000")Integer pageSize){

        AjaxResponseBody body = AjaxResponseBody.success();

        List<EsRoomInfo> esRoomInfoList = elasticSearchService.esRoomSearch(indexName, "cn", null, pageSize, pageNo);
        List<String> deleteIds = Lists.newArrayList();
        //List<String> useIds = Lists.newArrayList();
        if(!CollectionUtils.isEmpty(esRoomInfoList)){
            esRoomInfoList.forEach(esRoomInfo -> {

                List<EsRoomCalendarInfo> esRoomCalendarInfoList = elasticSearchService.queryCalendarByParentId(esRoomInfo.getSourceId(), indexName);
                if(CollectionUtils.isEmpty(esRoomCalendarInfoList)){
                    //删除房间
                    deleteIds.add(esRoomInfo.getRoomId());
                }
            });
        }

        log.info("删除的房间有：" + JSON.toJSONString(deleteIds));

        //log.info("有效的房间有：" + JSON.toJSONString(useIds));

        BulkResponse bulkItemResponses = elasticSearchService.deleteOverTimeCalendar(indexName, deleteIds);
        body.setBody(bulkItemResponses);
        return body;
    }


    //检验所有房间,如果没有房态，直接删除
    @ApiOperation("由酒店ID查询房间")
    @PostMapping("/del/hotel/roomIsNull")
    public AjaxResponseBody checkroom(@RequestParam(value = "pageNo", defaultValue = "1")Integer pageNo,
                                          @RequestParam(value = "indexName", defaultValue = "index_hotel") String indexName,
                                          @RequestParam(value = "pageSize", defaultValue = "1000")Integer pageSize){

        AjaxResponseBody body = AjaxResponseBody.success();

        List<EsHotelInfo> esHotelInfoList = elasticSearchService.esHotelSearch(indexName, "cn", null, pageSize, pageNo);
        List<String> deleteIds = Lists.newArrayList();
        if(!CollectionUtils.isEmpty(esHotelInfoList)){
            esHotelInfoList.forEach(esHotelInfo -> {

                List<EsRoomInfo> esRoomInfoList = elasticSearchService.queryByParentId(esHotelInfo.getSourceId(), indexName);
                if(CollectionUtils.isEmpty(esRoomInfoList)){
                    //删除酒店
                    deleteIds.add(esHotelInfo.getHotelId());
                }
            });
        }

        log.info("删除的酒店有：" + JSON.toJSONString(deleteIds));

        BulkResponse bulkItemResponses = elasticSearchService.deleteOverTimeCalendar(indexName, deleteIds);
        body.setBody(bulkItemResponses);
        return body;
    }

    @ApiOperation("V3.8.3删除酒店的所有房态")
    @PostMapping("/del/hotel/all/calendar")
    public AjaxResponseBody delHotelAllCalendar(@RequestParam(value = "hotelId")String hotelId,
                                                @RequestParam(value = "indexName", defaultValue = "index_hotel") String indexName){
        AjaxResponseBody body = null;
        BulkByScrollResponse bulkByScrollResponse = elasticSearchService.deleteCalendarByHotelId(hotelId, indexName);
        body = AjaxResponseBody.success(bulkByScrollResponse);
        return body;
    }


}
